<?php

/*============================================
Classe Competence
============================================*/

class Competence extends ModelObject{

	protected static $cached_object_list= array();
	protected $user;
	protected $instrument;

	protected function __construct( $user,$instrument){
		try{
			
			$this->user = $user;
			$this->instrument = $instrument;
		}
		catch(Excpetion $e){
			throw new Exception("La construction de l'objet de type get_class($this) a échouée",0,$e);
		}
	}

	public function getUser(){
		return User::get($this->user);
	}

	public function getInstrument(){
		return Instrument::get($this->instrument);
	}

	public function setUser( $user){
		try{
			$temp = $this->user;
			if(is_null($user)){
				throw new Exception("Le paramètre \$user de type get_class($user) est null alors que la colonne dans la base est marquée comme NOT NULL");
			}
			else if(!($user instanceof User) || is_null($user->getId())){
				throw new Exception("Le paramètre \$user de type get_class($user) n'est pas du bon type ou n'est pas présent dans la base");
			}
			else {
				if($this->user !== $user->getId()){
					$this->user = $user->getId();
					$this->update();
				}
			}
		}
		catch(Exception $e){
			$this->user = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setUser() a échouée",0,$e);
		}
	}

	public function setInstrument( $instrument){
		try{
			$temp = $this->instrument;
			if(is_null($instrument)){
				throw new Exception("Le paramètre \$instrument de type get_class($instrument) est null alors que la colonne dans la base est marquée comme NOT NULL");
			}
			else if(!($instrument instanceof Instrument) || is_null($instrument->getId())){
				throw new Exception("Le paramètre \$instrument de type get_class($instrument) n'est pas du bon type ou n'est pas présent dans la base");
			}
			else {
				if($this->instrument !== $instrument->getId()){
					$this->instrument = $instrument->getId();
					$this->update();
				}
			}
		}
		catch(Exception $e){
			$this->instrument = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setInstrument() a échouée",0,$e);
		}
	}

	public static function create( $user,$instrument){
		try{
			$competence = new Competence($user, $instrument);
			$competence->insert();
			Competence::cacheObject($competence);
			return $competence;
		}
		catch(Excpetion $e){
			throw new Exception("La création de l'objet de type Competence a échouée",0,$e);
		}
	}

	public static function get( $competence){
		$dbh = SingletonPDO::getInstance();
		try{
			if(is_null($competence) || $competence === "") {
				return null;
			}
			if(Competence::existsInCache($competence)) {
				return Competence::getFromCache($competence);
			}
			$dbh->beginTransaction();
			$sql= 'SELECT * FROM `competence` WHERE `competence` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':id'=>$competence));
			if ($row = $stmt->fetch()){
				$competence = new Competence( $row['user'],$row['instrument']);
				$competence->id =  $row['competence'];
				$dbh->commit();
				Competence::cacheObject($competence);
				return $competence;
			}
			else {
				$dbh->commit();
				return null;
			}
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La récupération de l'objet ayant l'id ". $competence . " a échouée",0,$e);
		}
	}

	protected function update(){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$sql='UPDATE `competence` SET `user` = :user, `instrument` = :instrument WHERE `competence` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':user'=>$this->user, ':instrument'=>$this->instrument, ':id'=>$this->id));
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La modification de l'objet de type ".get_class($this)." ayant l'id ". $this->id . " a échouée",0,$e);
		}
	}

	public function delete(){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$sql = 'DELETE FROM `competence` WHERE `competence` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':id'=>$this->id));
			Competence::removeObjectFromCache($this->id);
			$this->id = null;
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La suppression de l'objet de type ".get_class($this)." ayant l'id ". $this->id. " a échouée",0,$e);
		}
	}

	protected function insert(){
		$dbh = SingletonPDO::getInstance();
		try{
			if (is_null($this->id)) {
				$dbh->beginTransaction();
				$sql='INSERT INTO `competence` ( `user`, `instrument`) VALUES (:user, :instrument)';
				$stmt = $dbh->prepare($sql);
				$stmt->execute(array(':user'=>$this->user, ':instrument'=>$this->instrument));
				$this->id = $dbh->lastInsertId();
				$dbh->commit();
			}
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("L'insertion de l'objet de type ".get_class($this)." a échouée",0,$e);
		}
	}

	public static function getAll( $search_params = array(),$options = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			$objs = array();
			$sql = 'SELECT * FROM `competence`';
			$sql .= self::generateWhereClause($search_params);
			$sql .= self::generateOptionClause($options);
			$stmt = $dbh->prepare($sql);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$stmt->execute($array);
			while ($row = $stmt->fetch()) {
				$obj = null;
				if(Competence::existsInCache($row['competence'])){
					$obj = Competence::getFromCache($row['competence']);
				}
				else{
					$obj = new Competence( $row['user'],$row['instrument']);
				}
				if(!is_null($obj)){
					$obj->id = $row['competence'];
					Competence::cacheObject($obj);
					$objs[] = $obj;
				}
			}
			$dbh->commit();
			return $objs;
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La récuperation de la liste d'objets de type Competence a échouée",0,$e);
		}
	}

	public static function deleteAll( $search_params = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			$objs = array();
			$sql_delete = 'DELETE FROM `competence`';
			$sql_select = 'SELECT competence FROM `competence`';
			$sql_delete .= self::generateWhereClause($search_params);
			$sql_select .= self::generateWhereClause($search_params);
			$stmt_delete = $dbh->prepare($sql_delete);
			$stmt_select = $dbh->prepare($sql_select);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$var_select = $stmt_select->execute($array);
			$tab_to_delete_objects = $stmt_select->fetchAll();
			if(sizeof($tab_to_delete_objects) > 0){
				$var_delete = $stmt_delete->execute($array);
				foreach($tab_to_delete_objects as $ind => $row){
					$existing_object = Competence::getObjectFromCache($row['competence']);
					if(!is_null($existing_object)){
						$existing_object->id = null;
						Competence::removeObjectFromCache($row['competence']);
					}
				}
			}
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La suppression de la liste d'objets de type Competence a échouée",0,$e);
		}
	}

}